//
//  ReportFack3ViewController.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/10/18.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit
import TZImagePickerController
import YBImageBrowser
import RxSwift
import RxDataSources

class ReportFack3ViewController: BaseUIViewController {
    
    let timeText = TimeTextfield()
    let contentText = AddConnactTextField()
    
    let contentScrollView = UIScrollView()
    let contentView = UIView()
    var collectionView: DynamicCollectionView!
    var assetArray: [String] = []
    var imageIds: [String] = []
    
    let uploadViewModel = UploadImageViewModel()
    
    var editModel: FakeModel
    
    init(editModel: FakeModel) {
        self.editModel = editModel
        self.imageIds = editModel.ossList.map{ $0.id }
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = #colorLiteral(red: 0.9724436402, green: 0.972609818, blue: 0.9724331498, alpha: 1)
        self.navigationItem.title = "报假信息".localized
        
        contentScrollView.config
            .keyboardDismissMode(.onDrag)
            .alwaysBounceVertical(true)
            .backgroundColor(#colorLiteral(red: 0.9724436402, green: 0.972609818, blue: 0.9724331498, alpha: 1))
            .addTo(view)
            .makeConstraints { (make) in
                make.edges.equalToSuperview()
        }
        
        contentView.config
            .backgroundColor(.clear)
            .frame(x: 0, y: 0, width: SCREEN_WIDTH, height: 0)
            .addTo(contentScrollView)
        
        timeText.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(selectData)))
        contentView.addSubview(timeText)
        timeText.snp.makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.top.equalTo(10)
            make.height.equalTo(50)
        }
        
        contentText.config
            .text(editModel.content)
            .addTo(contentView)
            .extra {
                $0.placeHolder = "请描述现象".localized + "（非必填）".localized
        }.makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.top.equalTo(timeText.snp.bottom).offset(10)
            make.height.greaterThanOrEqualTo(140)
        }
        
        let itemWidht = (SCREEN_WIDTH - 40) / 3 - 1
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets.init(top: 15, left: 20, bottom: 15, right: 10)
        layout.minimumLineSpacing = 5
        layout.minimumInteritemSpacing = 5
        layout.itemSize = CGSize(width: itemWidht, height: itemWidht)
        
        collectionView = DynamicCollectionView.init(frame: .zero, collectionViewLayout: layout)
            .config
            .delegate(self)
            .dataSource(self)
            .register(ConnactImageCell.self)
            .backgroundColor(.white)
            .addTo(contentView)
            .makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(contentText.snp.bottom).offset(0)
        }.view
        
        let button = UIButton().config
            .backgroundImage(UIImage.imageWithColor(APPConfig.baseColor))
            .title("提交".localized)
            .cornerRadius(5)
            .clipsToBounds(true)
            .titleColor(.white)
            .addTarget(self, action: #selector(send))
            .addTo(contentView)
            .makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.left.equalTo(40)
                make.height.equalTo(50)
                make.top.equalTo(collectionView.snp.bottom).offset(40)
        }.view
        
        let text = NSMutableAttributedString.init(string: "提交后可前往 反馈 入口补充报假信息， 以便我们为您提供更好的帮助。".localized)
        text.setTextColor(APPConfig.baseColor, text: "反馈".localized)
        
        let bottomLabel = UILabel()
        bottomLabel.textAlignment = .center
        bottomLabel.textColor = #colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
        bottomLabel.numberOfLines = 0
        bottomLabel.font = UIFont.systemFont(ofSize: 12, weight: .medium)
        bottomLabel.attributedText = text
        self.contentView.addSubview(bottomLabel)
        bottomLabel.snp.makeConstraints { (make) in
            make.top.equalTo(button.snp.bottom).offset(20)
            make.centerX.equalToSuperview()
            make.left.equalTo(75)
        }
        
        if editModel.buyTime > 0 {
            let date = Date.init(timeIntervalSince1970: editModel.buyTime / 1000)
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd"
            timeText.timeLabel.text = formatter.string(from: date)
            timeText.timeLabel.textColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
            timeText.date = formatter.string(from: date)
        }
    }
    
    @objc func selectData() {
        var nowDate = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        
        if timeText.date.count > 0,
            let date = formatter.date(from: timeText.date) {
            nowDate = date
        }
        let datePicker = DatePickerDialog(textColor: .darkGray, buttonColor: .darkGray, font: UIFont.systemFont(ofSize: 15, weight: .medium), showCancelButton: true)
        datePicker.show("购买时间".localized, doneButtonTitle: "确定".localized, cancelButtonTitle: "取消".localized, defaultDate: nowDate, datePickerMode: .date) { [weak self] (date) in
            if let dt = date {
                self?.editModel.buyTime = Double(Int(dt.timeIntervalSince1970 * 1000))
                self?.timeText.timeLabel.text = formatter.string(from: dt)
                self?.timeText.timeLabel.textColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
                self?.timeText.date = formatter.string(from: dt)
            }
        }
    }
    
    func pickImage() {
        let tz = TZImagePickerController()
        tz.modalPresentationStyle = .fullScreen
        tz.maxImagesCount = 9 - self.assetArray.count - self.imageIds.count
        tz.navigationBar.barTintColor = APPConfig.baseColor
        tz.navigationBar.isTranslucent = false
        var locale = "en"
        if let userSelectLanguage = AppCache.shared.object(for: APPUserDefault.self).userSelectLanguage {
            switch userSelectLanguage {
            case .chinese:
                locale = "zh-Hans"
            case .english:
                locale = "en"
            case .de:
                locale = "en"
            case .vi:
                locale = "vi"
            }
        }
        tz.preferredLanguage = locale
        tz.allowTakeVideo = false
        tz.allowPickingVideo = false
        tz.pickerDelegate = self
        self.present(tz, animated: true, completion: nil)
    }
    
    @objc func send() {
        let text = self.contentText.text ?? ""
        editModel.content = text
        
        uploadViewModel.uploadImages(self.assetArray)
            .flatMap { [weak self] fileIds -> Observable<Void> in
                guard let self = self else {
                    return Observable.empty()
                }
                let api: ApiManager
                if self.editModel.id.count > 0 {
                    api = ApiManager.editFake(id: self.editModel.id,
                                              productNumber: self.editModel.productNumber,
                                              purchaseChannel: self.editModel.purchaseChannel,
                                              supplier: self.editModel.supplier,
                                              purchaseNum: self.editModel.purchaseNum,
                                              content: self.editModel.content,
                                              fileIds: self.imageIds + fileIds,
                                              contractNo: self.editModel.contractNo,
                                              buyTime: self.editModel.buyTime)
                } else {
                    api = ApiManager.reportFake(psrCheckId: self.editModel.psrCheckId,
                                                productNumber: self.editModel.productNumber,
                                                purchaseChannel: self.editModel.purchaseChannel,
                                                supplier: self.editModel.supplier,
                                                purchaseNum: self.editModel.purchaseNum,
                                                content: self.editModel.content,
                                                fileIds: self.imageIds + fileIds,
                                                contractNo: self.editModel.contractNo,
                                                buyTime: self.editModel.buyTime)
                }
                return api.request()
                    .trackingLoading()
                    .filterCode200()
                    .map{_ in }
                .post(.reloadFakeList)
        }.showSuccess(text: "报假信息提交成功".localized)
            .subscribe(onNext: { [weak self] (_) in
                self?.navigationController?.popViewController(2)
            }).disposed(by: rx.disposeBag)
    }
    
    override func navigationBarStyle() -> NavigationBarStyle {
        return .baseColor
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let maxY = contentView.subviews.map{ $0.frame.maxY }.max() ?? 0
        contentView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: maxY + UIApplication.shared.bottomSafeDistance + 20)
        contentScrollView.contentSize = contentView.size
    }
    
}

extension ReportFack3ViewController: TZImagePickerControllerDelegate {
    
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage], sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool) {
        let photosModel = photos
            .map { image -> String in
                let randomString = String.random() + "\(Date().timeIntervalSince1970)"
                return image.writeToFileName(name: randomString.md5() + ".png")
        }
        self.assetArray += photosModel
        self.collectionView.reloadData()
    }
    
}

extension ReportFack3ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return min(imageIds.count + assetArray.count + 1, 9)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(ConnactImageCell.self, for: indexPath)
        if indexPath.item == imageIds.count + assetArray.count {
            cell.imageView.image = UIImage.init(named: "add_button")
            cell.deleteButton.isHidden = true
        } else {
            if indexPath.row < imageIds.count {
                cell.imageView.sd_setImage(with: URL.init(string: APPConfig.imagePath + self.imageIds[indexPath.item]), placeholderImage: UIImage.init(named: "placeholder_image"), options: .retryFailed, context: nil)
            } else {
                cell.imageView.setImageWith(contentsOfFile: self.assetArray[indexPath.item - self.imageIds.count])
            }
            cell.deleteButton.isHidden = false
        }
        cell.deleteBlock = { [weak self] in
            guard let self = self else { return }
            if indexPath.row < self.imageIds.count {
                self.imageIds.remove(at: indexPath.item)
            } else {
                self.assetArray.remove(at: indexPath.item - self.imageIds.count)
            }
            collectionView.reloadData()
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item == imageIds.count + assetArray.count {
            pickImage()
            return
        }
        
        let browser = YBImageBrowser.init()
        browser.toolViewHandlers = []
        browser.dataSource = self
        browser.currentPage = indexPath.item
        browser.show()
    }
    
}

extension ReportFack3ViewController: YBImageBrowserDataSource {
    
    func yb_numberOfCells(in imageBrowser: YBImageBrowser) -> Int {
        return imageIds.count + assetArray.count
    }
    
    func yb_imageBrowser(_ imageBrowser: YBImageBrowser, dataForCellAt index: Int) -> YBIBDataProtocol {
        let cell = collectionView.cellForItem(at: IndexPath.init(item: Int(index), section: 0)) as? ConnactImageCell
        let data = YBIBImageData()
        if index < imageIds.count {
            data.imageURL = URL.init(string: APPConfig.imagePath + imageIds[index])
        } else {
            data.imagePath = assetArray[index - self.imageIds.count]
        }
        data.projectiveView = cell?.imageView
        return data
    }
    
}
